﻿using AutoMapper;
using Management.Systeam.Domaina;
using Management.Systeam.ErrorCode;
using Management.Systeam.Infrastructure.Interface;
using Management.Systeam.Write.Api.Application.Command.Rolees;
using MediatR;

namespace Management.Systeam.Write.Api.Application.CommandHandler.Rolees
{
    public class AddRoleCommandHandler : IRequestHandler<AddRoleCommand, ApiResult<int>>
    {
        IBaseRepository<Users> Users;
        IBaseRepository<RoleUser> RoleUser;
        IBaseRepository<Role> Role;
        IMapper mapper;

        public AddRoleCommandHandler(IBaseRepository<Users> Users, IBaseRepository<RoleUser> RoleUser, IBaseRepository<Role> Role, IMapper mapper)
        {
            this.Users = Users;
            this.RoleUser = RoleUser;
            this.Role = Role;
            this.mapper = mapper;
        }

        public async Task<ApiResult<int>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> apiResult = new ApiResult<int>();
            try
            {
                var model = mapper.Map<Role>(request);
                int r = Role.InsertAsync(model).Result;
                if (r > 0)
                {
                    apiResult.Code = ApiEnum.success;
                    apiResult.Message = "添加成功";
                }

            }
            catch (Exception ex)
            {
                apiResult.Code = ApiEnum.error;
                apiResult.Message = ex.Message;

            }
            return apiResult;
        }
    }
}
